package com.token.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.token.service.QrCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: henriy
 * @Date: 2024/8/8
 */
@Slf4j
@Service
public class QrCodeServiceImpl implements QrCodeService {

    @Override
    public void codeDownloadLogo(HttpServletResponse response) {
        String name = "嘻嘻哈哈";
        String qrCodeContent = "扫描二维码中的文本内容";
        QrConfig config = new QrConfig(400, 400);
        config.setMargin(1);
        config.setForeColor(new Color(0, 0, 0));
        config.setBackColor(new Color(255, 255, 255));
        try {
            String logoPath = ResourceUtils.getFile("classpath:picture/logo.png").getPath();
            config.setImg(logoPath);
            config.setErrorCorrection(ErrorCorrectionLevel.H);
            byte[] pngArr = QrCodeUtil.generatePng(String.format("%s&biz_no=%s", qrCodeContent, name), config);
            response.setContentType("application/octet-stream;charset=utf-8");
            String fileName = new String((name + ".png").getBytes(), "iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.getOutputStream().write(pngArr, 0, pngArr.length);
        } catch (IOException e) {
            throw new RuntimeException("导出异常");
        }
    }

    @Override
    public void codeDownloadBackground(HttpServletResponse response) {
        BufferedImage backgroundImage;
        BufferedImage logoImage;
        try {
            // 背景图、logo
            URL backgroundUrl = new URL("https://rfhz-dev.oss-cn-hangzhou.aliyuncs.com/xunwang/template/background_home.png");
            backgroundImage = ImageIO.read(backgroundUrl);

            URL logoUrl = new URL("https://rfhz-dev.oss-cn-hangzhou.aliyuncs.com/xunwang/template/logo.png");
            logoImage = ImageIO.read(logoUrl);
        } catch (IOException e) {
            log.error("background and logo image read error, message:{}", e.getMessage());
            throw new RuntimeException("图片读取异常");
        }

        String qrText = "扫二维码实际跳转的内容，一般是http地址";
        // 二维码尺寸
        int qrSize = 250;
        BufferedImage qrCodeImage = generateQRCode(qrText, qrSize, logoImage);
        // 设置二维码的上下位置
        int qrX = (backgroundImage.getWidth() - qrSize) / 2;
        int qrY = 420;
        addImageToImage(backgroundImage, qrCodeImage, qrX, qrY);

        // 图片上添加中文文本
        String chineseText = "x嘻嘻呼呼";
        Font font = new Font("微软雅黑", Font.PLAIN, 40);
        // 文本颜色
        Color textColor = Color.BLACK;
        // 文本左侧的边距
        int textX = 20;
        // 设置文本的垂直位置200
        int textY = 750;
        // 文本可用的宽度，读取底图宽度
        int textWidth = backgroundImage.getWidth();
        addTextToImage(backgroundImage, chineseText, font, textColor, textWidth, textY);

        try {
            response.setContentType("image/png");
            //response.setHeader("Content-Disposition", "attachment; filename=\"output.png\"");
            String name = "嘻嘻哈哈";
            String fileName = new String((name + ".png").getBytes(), "iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            OutputStream os = response.getOutputStream();
            ImageIO.write(backgroundImage, "png", os);
            os.close();
        } catch (IOException e) {
            throw new RuntimeException("导出异常");
        }
    }

    /**
     * 生成二维码图片
     *
     * @param text 二维码需扫描的文本内容
     * @param size 二维码大小
     * @return
     */
    private static BufferedImage generateQRCode(String text, int size, BufferedImage logoImage) {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix;
        QRCodeWriter writer = new QRCodeWriter();

        try {
            bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, size, size, hints);
        } catch (WriterException e) {
            throw new RuntimeException("二维码生成异常");
        }

        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        log.info("qrcode width={}, height={}", width, height);

        int logoWidth = logoImage.getWidth();
        int logoHeight = logoImage.getHeight();
        log.info("logo width={}, height={}", logoWidth, logoHeight);

        int logoX = (width - logoWidth) / 2;
        int logoY = (height - logoHeight) / 2;
        log.info("logoX={}, logoY={}", logoX, logoY);

        BufferedImage qrImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = qrImage.createGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, size, size);
        graphics.setColor(Color.BLACK);
        // 二维码中嵌入logo
        graphics.drawImage(logoImage, logoX, logoY, logoWidth, logoHeight, null);

        // 画码
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                // 忽略logo部分画码
                if (x >= logoX && x <= logoX + logoWidth && y >= logoY && y <= logoY + logoHeight) {
                    continue;
                }

                if (bitMatrix.get(x, y)) {
                    graphics.fillRect(x, y, 1, 1);
                }
            }
        }

        // 渲染二维码
        Graphics2D graphics1 = qrImage.createGraphics();
        // 边框大小、颜色
        int borderSize = 1;
        Color myColor = new Color(10, 105, 255);
        graphics1.setColor(myColor);
        // 上、左、右、下边框
        graphics1.fillRect(0, 0, size, borderSize);
        graphics1.fillRect(0, 0, borderSize, size);
        graphics1.fillRect(size - borderSize, 0, borderSize, size);
        graphics1.fillRect(0, size - borderSize, size, borderSize);
        return qrImage;
    }

    /**
     * 在图片上添加图片
     *
     * @param baseImage
     * @param overlayImage
     * @param x
     * @param y
     */
    private static void addImageToImage(BufferedImage baseImage, BufferedImage overlayImage, int x, int y) {
        Graphics2D g2d = baseImage.createGraphics();
        g2d.drawImage(overlayImage, x, y, null);
        g2d.dispose();
    }

    /**
     * 在图片上添加文本，支持手动换行，文本水平居中
     *
     * @param baseImage
     * @param text
     * @param font
     * @param color
     * @param maxWidth
     * @param y
     */
    private static void addTextToImage(BufferedImage baseImage, String text, Font font, Color color, int maxWidth, int y) {
        Graphics2D g2d = baseImage.createGraphics();
        g2d.setFont(font);
        g2d.setColor(color);

        FontMetrics fm = g2d.getFontMetrics();
        int lineHeight = fm.getHeight();
        int currentY = y;
        String[] lines = text.split("\n");

        for (String line : lines) {
            int lineWidth = fm.stringWidth(line);
            // 居中
            int lineX = (maxWidth - lineWidth) / 2;
            g2d.drawString(line, lineX, currentY);
            currentY += lineHeight;
        }

        g2d.dispose();
    }


}
